<?php


function log_action($msg) {
  $today = date("d.m.Y");
  $filename = "/Volumes/Datum/Web/Archiv/Dokumenty/requests_$today.log";
  $fd = fopen($filename, "a");
  $str = "[" . date("d/m/Y h:i:s", mktime()) . "] " . $msg;
  fwrite($fd, $str . PHP_EOL);
  fclose($fd);
}
//Read more at http://www.devshed.com/c/a/PHP/Logging-With-PHP/#



$filename = $_GET['id'];


//print_r($_REQUEST);

$directory = "/Volumes/Datum/Web/Archiv/Dokumenty/";
$sql_data=$_GET['sql'];


$name = $_GET['jmeno'];
$rok = $_GET['rok'];
$eventid = $_GET['id'];



log_action("Request id $eventid type ". $sql_data['type'] ." from $name");


switch ($sql_data['type']) {
  case 1:
    $datefrom = $_GET['od'];
    $dateto = $_GET['do'];
    $days = $_GET['dnu'];
    $date = $_GET['dne'];
    //$tex_cmd = "\\Dovolena{".$name."}{".$rok."}{".$datefrom."}{".$dateto."}{".$days."}\n";
    $tex_cmd="";
    foreach ($_GET['DovolenaMesicne'] as $M){
      $tex_cmd = $tex_cmd . "\\Dovolena{".$name."}{".$M['rok']."}{".$M['od']."}{".$M['do']."}{".$M['dnu']."}{".$date."}{".$eventid."}\n";

    }

    //print_r($_GET['DovolenaMesicne']);
    break;

  case 2:
    $datefrom = $_GET['odY'];
    $dateto = $_GET['doY'];
    $place = $sql_data['DestinationCity'];
    $country=$sql_data['DestinationCountry'];
    $address=$_GET['adresa'];
    $reason = $sql_data['Reason'];
    $grant = $_GET['granty'];
    $tex_cmd = "\\Cestak{".$name."}{".$datefrom."}{".$dateto."}{".$place."}{".$reason."}{".$grant."}{".$address."}{".$country."}{".$eventid."}\n";
    break;
}


$myFileTex = "Dokumenty/".$filename.".tex";
$myFilePdf = "Dokumenty/".$filename.".pdf";
$fh = fopen($myFileTex, 'w');

fwrite($fh, "% !TEX encoding = UTF-8 Unicode\n\\input{Vogoni.tex}\n\\begin{document}\n");
fwrite($fh, $tex_cmd);
fwrite($fh, "\\end{document}");

fclose($fh);

# Run PDF maker ---------------------------------------------------------------------&gt;

$msg = exec("cd $directory; /usr/texbin/pdflatex $filename.tex", $pdfgen);

if($pdfgen == 1){
  echo "Due to an attack, we were unable to generate a PDF: ";
  echo $msg;
  log_action("FAILED Request id $eventid");
  exit;
}


// return the pdf file
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($myFilePdf));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($myFilePdf));
ob_clean();
flush();
readfile($myFilePdf);

// close log file
$log->lclose();

?>
